package com.cloud.pole.msg.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpClientService {

    private static final String CHARSET = "UTF-8";
    private static final String CONTENT_JSON = "application/json";
    private static final String CONTENT_URL_ENCODED = "application/x-www-form-urlencoded";

    /**
     * 发送post请求(json)
     *
     * @param params  params
     * @param httpUrl url
     * @return response
     */
    public static Map<String, Object> httpPost(Map<String, String> params, String httpUrl) {
        Map<String, Object> mp = new HashMap<>();
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpClientContext context = HttpClientContext.create();
            StringEntity entity = new StringEntity(JSON.toJSONString(params), CHARSET);
            HttpPost post = new HttpPost(httpUrl);

            post.setEntity(entity);
            entity.setContentType(CONTENT_JSON);

            CloseableHttpResponse response = client.execute(post, context);
            int statusCode = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity(), CHARSET);

            mp.put("statusCode", statusCode);
            mp.put("response", result);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return mp;
    }

    /**
     * 发送post请求(multipart/form-data)
     *
     * @param params  params
     * @param httpUrl url
     * @return response
     */
    public static Map<String, Object> httpPostForm(Map<String, String> params, String httpUrl) {
        Map<String, Object> mp = new HashMap<>();
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpClientContext context = HttpClientContext.create();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            for (String key : params.keySet()) {
                log.info("本次post请求的参数为: {" + key + ": " + params.get(key) + "}");
                if (StringUtils.isNoneBlank(params.get(key))) {
                    builder.addPart(key, new StringBody(params.get(key), ContentType.TEXT_PLAIN));
                }
            }

            HttpPost post = new HttpPost(httpUrl);
            post.setEntity(builder.build());

            CloseableHttpResponse response = client.execute(post, context);
            String result = EntityUtils.toString(response.getEntity(), CHARSET);

            return JSON.parseObject(result);
        } catch (IOException e) {
            log.error(e.getMessage(), e.getCause());
        }
        return mp;
    }

    /**
     * 发送GET请求（with Token）
     *
     * @param token   令牌
     * @param httpUrl 访问地址
     * @return result
     */
    public static String httpGet(String token, String httpUrl) {
        String result = "";
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(httpUrl);
            if (StringUtils.isNoneBlank(token)) {
                get.setHeader("token", token);
            }
            CloseableHttpResponse response = client.execute(get);
            result = EntityUtils.toString(response.getEntity(), CHARSET);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
